{extend name='admin@main'}

{block name="content"}

<script>
layui.use('upload', function(){
  var $ = layui.jquery
  ,upload = layui.upload;
  
  //普通图片上传
  var uploadInst = upload.render({
    elem: '#test1'
    ,url: '/upload/'
    ,before: function(obj){
      //预读本地文件示例，不支持ie8
      obj.preview(function(index, file, result){
        $('#demo1').attr('src', result); //图片链接（base64）
      });
    }
    ,done: function(res){
      //如果上传失败
      if(res.code > 0){
        return layer.msg('上传失败');
      }
      //上传成功
    }
    ,error: function(){
      //演示失败状态，并实现重传
      var demoText = $('#demoText');
      demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
      demoText.find('.demo-reload').on('click', function(){
        uploadInst.upload();
      });
    }
  });
  
  //多图片上传
  upload.render({
    elem: '#test2'
    ,url: '/upload/'
    ,multiple: true
    ,before: function(obj){
      //预读本地文件示例，不支持ie8
      obj.preview(function(index, file, result){
        $('#demo2').append('<img src="'+ result +'" alt="'+ file.name +'" class="layui-upload-img">')
      });
    }
    ,done: function(res){
      //上传完毕
    }
  });
  
  //指定允许上传的文件类型
  upload.render({
    elem: '#test3'
    ,url: '/upload/'
    ,accept: 'file' //普通文件
    ,done: function(res){
      console.log(res)
    }
  });
  upload.render({ //允许上传的文件后缀
    elem: '#test4'
    ,url: '/upload/'
    ,accept: 'file' //普通文件
    ,exts: 'zip|rar|7z' //只允许上传压缩文件
    ,done: function(res){
      console.log(res)
    }
  });
  upload.render({
    elem: '#test5'
    ,url: '/upload/'
    ,accept: 'video' //视频
    ,done: function(res){
      console.log(res)
    }
  });
  upload.render({
    elem: '#test6'
    ,url: '/upload/'
    ,accept: 'audio' //音频
    ,done: function(res){
      console.log(res)
    }
  });
  
  //设定文件大小限制
  upload.render({
    elem: '#test7'
    ,url: '/upload/'
    ,size: 60 //限制文件大小，单位 KB
    ,done: function(res){
      console.log(res)
    }
  });
  
  //同时绑定多个元素，并将属性设定在元素上
  upload.render({
    elem: '.demoMore'
    ,before: function(){
      layer.tips('接口地址：'+ this.url, this.item, {tips: 1});
    }
    ,done: function(res, index, upload){
      var item = this.item;
      console.log(item); //获取当前触发上传的元素，layui 2.1.0 新增
    }
  })
  
  //选完文件后不自动上传
  upload.render({
    elem: '#test8'
    ,url: '/upload/'
    ,auto: false
    //,multiple: true
    ,bindAction: '#test9'
    ,done: function(res){
      console.log(res)
    }
  });
  
  //拖拽上传
  upload.render({
    elem: '#test10'
    ,url: '/upload/'
    ,done: function(res){
      console.log(res)
    }
  });
  
	//多文件列表示例
	var demoListView = $('#demoList'),
	uploadListIns = upload.render({
		elem: '#testList',
		url: '{:url("upload")}',
		accept: 'file',
		multiple: true,
		auto: false,
		bindAction: '#testListAction',
		choose: function(obj) {
			var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
			//读取本地文件
			obj.preview(function(index, file, result) {
			
				//console.log(index);
				
				var tr = $(['<tr id="upload-' + index + '">', '<td>' + file.name + '</td>', '<td>' + (file.size / 1014).toFixed(1) + 'kb</td>', '<td>等待上传</td>', '<td>', '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>', '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>', '</td>', '</tr>'].join(''));

				//单个重传
				tr.find('.demo-reload').on('click',
				function() {
					obj.upload(index, file);
				});

				//删除
				tr.find('.demo-delete').on('click',
				function() {
					delete files[index]; //删除对应的文件
					tr.remove();
					uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
				});

				demoListView.append(tr);
			});
		},
		done: function(res, index, upload) {
			console.log(res);
			
			
			//console.log(upload);
			if (res.code == 0) { //上传成功
				var tr = demoListView.find('tr#upload-' + index),
				tds = tr.children();
				var str ='<input type="hidden" name="fileurl[]" value="'+res.url+'"><input type="hidden" name="user_id[]" value="'+res.user_id+'">';
				str +='<input type="hidden" name="original_name[]" value="'+res.original_name+'"><input type="hidden" name="fileext[]" value="'+res.extension+'">';
				str +='<input type="hidden" name="filesize[]" value="'+res.size+'"><input type="hidden" name="filename[]" value="'+res.save_name+'">';
				str +='<input type="hidden" name="md5code[]" value="'+res.md5+'"><input type="hidden" name="sha1code[]" value="'+res.sha1+'">';
				
				tds.eq(2).html('<span style="color: #5FB878;">上传成功'+str+'</span>');
				tds.eq(3).html('<a href="'+res.url+'" target="new">查看</a>'); //清空操作
				return delete this.files[index]; //删除文件队列已经上传成功的文件
			}
			this.error(index, upload);
		},
		error: function(index, upload) {
			var tr = demoListView.find('tr#upload-' + index),
			tds = tr.children();
			tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
			tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
		}
	});
  
  //绑定原始文件域
  upload.render({
    elem: '#test20'
    ,url: '/upload/'
    ,done: function(res){
      console.log(res)
    }
  });
  
});
</script>



<form class="layui-form layui-card" action="{:request()->url()}"  onsubmit="return false;" data-auto="true" method="post" autocomplete="off" id="Newform">

    <div class="layui-card-body think-box-shadow padding-left-40">
	
		<blockquote class="layui-elem-quote">
		
			<span class="layui-badge layui-bg-green">在某些浏览器下，页面可能加载不完整，如果出现这种情况，请按F5重新加载页面!</span>
			&nbsp;
			<button type="button" data-reload="" class="layui-btn layui-btn-danger layui-btn-xs">刷 新</button>
		  
		</blockquote>

        <div class="layui-form-item">
            <label class="layui-form-label ">新闻标题</label>
            <div class="layui-input-block">
				<input name="title" id="title" value='{$vo.title|default=""}' required placeholder="请输入文件标题" class="layui-input">
            </div>
        </div>


		<div class="layui-form-item nowrap">
		  <label class="layui-form-label label-required label-required-next">发布网址</label>
		  <div class="layui-input-inline margin-right-0" style="width:200px">
			<input name="docurl" value='{$vo.docurl|default="http://www.fslks.com/"}' placeholder="请输入发布网址" class="layui-input">
		   </div>
		  <label class="layui-form-label ">发 布 人</label>
		  <div class="layui-input-inline margin-right-0" style="width:200px;">
		    <input type="text" name="docauthor" value='{$vo.docauthor|default=session("admin_user.nickname")}'  placeholder="" class="layui-input" >
		  </div>

		</div>


		<div class="layui-form-item nowrap">
		  <label class="layui-form-label label-required label-required-next">发布时间</label>
		  <div class="layui-input-inline margin-right-0" style="width:200px">
			<input type="text" data-date-input="date" name="docdate" value='{$vo.docdate|format_datetime='Y-m-d'}' required placeholder="发布时间" class="layui-input" >
		   </div>
		  <label class="layui-form-label ">联系电话</label>
		  <div class="layui-input-inline margin-right-0" style="width:200px;">
		    <input type="text" name="doctel" value='{$vo.doctel|default=""}'  placeholder="" class="layui-input" >
		  </div>

		</div>
		
	
		
		<!--
        <div class="layui-form-item">
            <label class="layui-form-label label-required">科室/项目负责人</label>
            <div class="layui-input-block">
                <div id="keshifuzeren" class="xm-select-demo"></div>
            </div>
        </div>
		
		
        <div class="layui-form-item">
            <label class="layui-form-label ">收发文员/拟稿人</label>
            <div class="layui-input-block">
				<div id="shouwenwenyuan" class="xm-select-demo"></div>
            </div>
        </div>
		-->

        <div class="layui-form-item">
            <label class="layui-form-label ">新闻内容（提纲）</label>
            <div class="layui-input-block">
	<!-- <script type="text/plain" class="js-ueditor" styke="z-index:-999" id="content" name="content">{$vo.content|default=''|raw}</script> -->
				<!-- <textarea class="layui-textarea" name="content" id="content" style="height: 450px;">{$vo.content|default=''|raw}</textarea> -->
            
  <textarea name="content" id="content" style="width:99%;height:400px;">{$vo.content|default=''|raw}</textarea>		
			
			
			</div>
        </div>
		
        <div class="layui-form-item">
            <label class="layui-form-label ">科室/项目负责人</label>
            <div class="layui-input-block">
                <div id="keshifuzeren" class="xm-select-demo"></div>
            </div>
        </div>
		

        <div class="layui-form-item">
            <label class="layui-form-label ">办公室主任</label>
            <div class="layui-input-block">
				<div id="bangongshizhuren" class="xm-select-demo"></div>
            </div>
        </div>
		

        <div class="layui-form-item">
            <label class="layui-form-label ">分管领导</label>
            <div class="layui-input-block">
				<div id="fenguanlingdao" class="xm-select-demo"></div>
            </div>
        </div>
		
        <div class="layui-form-item">
            <label class="layui-form-label ">网站发布人</label>
            <div class="layui-input-block">
				<div id="shouwenwenyuan" class="xm-select-demo"></div>
            </div>
        </div>
		





		
        <div class="layui-form-item">
            <label class="layui-form-label ">文件列表</label>
            <div class="layui-input-block">
                <div class="layui-textarea padding-bottom-10" style="min-height:auto">
					<div class="layui-upload">
					  {if auth("edit") && request()->action() =='edit'  && $vo['docauthor']==session('admin_user')['nickname'] && $vo['status']!=2 }
					  <button type="button" class="layui-btn layui-btn-normal layui-btn-sm" id="testList">选择多文件</button> &nbsp;&nbsp;
					  <button type="button" class="layui-btn layui-btn-sm" id="testListAction">开始上传</button>
					  {/if}
					  
					  {if auth("add") && request()->action() =='add'  }
					  <button type="button" class="layui-btn layui-btn-normal layui-btn-sm" id="testList">选择多文件</button> &nbsp;&nbsp;
					  <button type="button" class="layui-btn layui-btn-sm" id="testListAction">开始上传</button>
					  {/if}				  

					  <div class="layui-upload-list">
						<table class="layui-table">
						  <thead>
							<tr><th>文件名</th>
							<th>大小</th>
							<th>状态</th>
							<th>操作</th>
						  </tr></thead>
						  <tbody id="demoList">
						  {foreach $files as $key=>$vo}
						  <tr id="upload-{$vo.id}"><td>{$vo.original_name}</td><td>{$vo.filesize|format_size}</td><td></td><td> <a target="new" href="{$vo.fileurl}">查看</a></td>  <tr>
						  {/foreach}
						  </tbody>
						</table>
					  </div>
					  
					</div> 


                </div>
            </div>
        </div>
		

		{if request()->action() =='edit'}
        <div class="layui-form-item">
            <label class="layui-form-label ">批示情况</label>
            <div class="layui-input-block">
                <div class="layui-textarea padding-bottom-10" style="min-height:auto">

						<table class="layui-table">
						  <thead>
							<tr>
							<th>批示人</th>
							<th>批示时间</th>
							<th>批示类型</th>
							<th>批改内容</th>
							<th width="164px">批示内容</th>
						  </tr></thead>
						  {foreach $list_flow as $key=>$vo}
						  <tr id="upload-{$vo.id}">
						  <td>{$vo.username}</td>
						  <td>{$vo.addtime|format_datetime='Y-m-d H:i'}</td>
						  
						  <td>                
						  {eq name='vo.types' value='nigao'}<span class="layui-bg-red">拟稿完成</span>{/eq}
						  {eq name='vo.types' value='keshifuzeren'}<span class="layui-bg-orange">科室/项目负责人审核</span>{/eq}
						  {eq name='vo.types' value='shouwenwenyuan'}<span class="layui-bg-green">发文文员/拟稿人重核</span>{/eq}
						  {eq name='vo.types' value='bangongshizhuren'}<span class="layui-bg-blue">办公室主任</span>{/eq}
						  {eq name='vo.types' value='fenguanlingdao'}<span class="layui-bg-black">分管领导</span>{/eq}
						  {eq name='vo.types' value='zhuyaolingdao'}<span class="layui-bg-gray">主要领导</span>{/eq}
						  </td>
						  <th>
						  {if $vo.files !=''}
						  <a href="{$vo.files}" target="new">查看</a> &nbsp;<a href="javascript:void(0)" id="quote" onclick="quote('{$vo.files}')">引用</a> &nbsp;&nbsp;
						  {/if}
						  </th>
						  
						  <td> {$vo.info}</td>  <tr>
						  {/foreach}
						</table>

                </div>
            </div>
        </div>
		{/if}


		{if request()->action() =='edit' && $rs_flow >0 && $my_flow_count ==0 }
        <div class="layui-form-item">
            <label class="layui-form-label">填写意见</label>
            <div class="layui-input-block">
				<textarea class="layui-textarea" name="info" id="info" placeholder="请填写批示意见">{$info|default=""}</textarea>
            </div>
			
        </div>
		
        <div class="layui-form-item">
            <label class="layui-form-label">原文修订</label>
            <div class="layui-input-block">
			  <select name="modify" id="modify" lay-verify="required">
				<option value=""></option>
				<option value="0">无修改</option>
				<option value="1">有修改</option>
			  </select>
            </div>
			
        </div>
		{/if}

        <div class="layui-form-item text-center">
            {notempty name='id'}<input type="hidden" name="id" id="id" value="{$id}">{/notempty}

			<input type='hidden' value='{$docauthor}' name='docauthor'>
			{if request()->action() =='edit' && $rs_flow >0 && $my_flow_count ==0 }
			<button class="layui-btn" type='button' id="saveinfo">保存批示意见</button>
			{/if}
			
			{if request()->action() =='edit' && $docauthor == session('admin_user.nickname')  }
			<button class="layui-btn" type='submit'>流转文件</button>
			{/if}
			
			{if request()->action() =='add' }
			<button class="layui-btn" type='submit'>保存数据</button>
			{/if}
			<button class="layui-btn layui-btn-danger" onclick="hsitoryBack()" type="button">关闭</button>
        </div>

    </div>
</form>
{/block}


	
{block name='script'}

<!-- <link href="__ROOT__/static/plugs/select2/dist/css/select2.min.css" rel="stylesheet" /> -->
<!-- <script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script> -->
<!-- <script src="__ROOT__/static/plugs/select2/dist/js/select2.min.js"></script> -->
	<script src="__ROOT__/static/ewebeditor/5-1-5/tinymce.min.js"></script>

	<script src="__ROOT__/static/plugs/select/xm-Select.js"></script>
	<script src="__ROOT__/static/base64.js"></script>

<script>
  //tinymce.PluginManager.load('moxiemanager', '/static/plugs/tinymce/plugins/moxiemanager/plugin.min.js');
  tinymce.init({
		language: "zh_CN",
		//theme: 'silver',
		
		
		selector: 'textarea#content',//意思是将TinyMCE插件放入‘textarea’ID为mytextarea的标签里
		
		hasChange: false,
		hasInit: false,
		menubar: true,
		body_class: 'panel-body ',
		object_resizing: false,
		end_container_on_empty_block: true,

		code_dialog_height: 450,
		code_dialog_width: 1000,
		advlist_bullet_styles: 'square',
		advlist_number_styles: 'default',
		imagetools_cors_hosts: ['www.tinymce.com', 'codepen.io'],
		default_link_target: '_blank',
		link_title: false,
		//content_css: 'css/content.css',

		
	    powerpaste_word_import: 'propmt', // 参数可以是propmt, merge, clear，效果自行切换对比
	    powerpaste_html_import: 'propmt', // propmt, merge, clear
	    powerpaste_allow_local_images: true,
		nonbreaking_force_tab: true, // inserting nonbreaking space &nbsp; need Nonbreaking Space Plugin
		plugins: [ //配置插件：可自己随意选择，但如果是上传本地图片image和imagetools是必要的 
		  'imagetools  image code link autolink table emoticons template paste preview media' //contextmenu   textcolor moxiemanager
		  //advlist autolink link  lists charmap print preview hr anchor pagebreak spellchecker',
		  //'searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking',
		  //'save table     directionality emoticons template paste 
		],
		//工具框，也可自己随意配置
		toolbar: 'insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image | print preview media fullpage | forecolor backcolor emoticons',   	
		image_advtab: true,
		table_default_styles: {
			width: '98%',
			borderCollapse: 'collapse'
		},


	file_browser_callback: function(field_name, url, type, win) {
		console.log(field_name);
		win.document.getElementById(field_name).value = 'my browser value';
	},

    file_picker_types: 'file image media',
	file_picker_callback: function(callback, value, meta) {
		// Provide file and text for the link dialog
		/*
		if (meta.filetype == 'file') {
		  callback('mypage.html', {text: 'My text'});
		}

		// Provide image and alt text for the image dialog
		if (meta.filetype == 'image') {
		  callback('myimage.jpg', {alt: 'My alt text'});
		}

		// Provide alternative source and posted for the media dialog
		if (meta.filetype == 'media') {
		  callback('movie.mp4', {source2: 'alt.ogg', poster: 'image.jpg'});
		}*/

	    /*
	      Note: In modern browsers input[type="file"] is functional without
	      even adding it to the DOM, but that might not be the case in some older
	      or quirky browsers like IE, so you might want to add it to the DOM
	      just in case, and visually hide it. And do not forget do remove it
	      once you do not need it anymore.
	    */
	    var input = document.createElement('input');
	    input.setAttribute('type', 'file');
	    input.setAttribute('id', 'files');
	    //input.setAttribute('enctype', 'multipart/form-data'); //enctype="multipart/form-data" 

	    if (meta.filetype == 'image') {
	    	input.setAttribute('accept', 'image/*');
		    input.onchange = function (e) {
		    	var file = this.files[0];

		    	var reader = new FileReader();
		    	reader.readAsDataURL(file);	//读出 base64
		    	/*
				reader.onload = function () {

				    var id = 'blobid' + (new Date()).getTime();
				    var blobCache =  tinymce.activeEditor.editorUpload.blobCache;
				    var base64 = reader.result.split(',')[1];
				    var blobInfo = blobCache.create(id, file, base64);

					//console.log(base64)
					blobCache.add(blobInfo);

					//console.log(blobInfo.blobUri());

					//callback(blobInfo.blobUri(), { title: file.name });
				};
				*/
		      	
		        reader.onloadend = function (e) {
		        	var data = e.target.result; //获取数据
		        	//console.log(data);
		            // 图片的base64值
		            var data_64= reader.result.substring(reader.result.indexOf(",")+1);
		            //console.log(data_64)

					$.post("{:url("savepic")}",{picdata:data},function(res){
						//console.log(base64);
						if(res.code =='0'){	
							callback(res.url, { title: file.name });
							//alert(res.info);
							layer.msg(res.info);
						}else{
							layer.msg('保存失败');
						}
					});	


		            if(isCanvasSupported()){
		                 //ajaxUploadBase64File(data);
		            }else{
		                 alert("您的浏览器不支持");
		            }

		        };
		    };
	    }


		if (meta.filetype == 'file') {
			//alert('file');
		  	//input.setAttribute('accept', '*/*');
		  	input.setAttribute('accept', '.xls,.xlsx,.doc,.docx,.ppt,.pdf,.pptx,.zip,.rar,.7z');
		    input.onchange = function (e) {
		    	var file = this.files[0];
		    	//alert('上传文件后缀名为：' + this.value.toLowerCase().split('.').splice(-1));
		    	var ext =this.value.toLowerCase().split('.').splice(-1);

		    	/*
				const LENGTH = 1024 * 1024 * 10;//每次上传的大小
				//var file = document.getElementsByName('video')[0].files[0];//文件对象
				var filename=file.name;
				var totalSize = file.size;//文件总大小
				var start = 0;//每次上传的开始字节
				var end = start + LENGTH;//每次上传的结尾字节
				var fd = null;//创建表单数据对象
				var blob = null;//二进制对象
				var xhr = null;//xhr对象
				while(start < totalSize){
					fd = new FormData();//每一次需要重新创建
					xhr = new XMLHttpRequest();//需要每次创建并设置参数
					xhr.open('POST', "{:url(uploadBin)}?ext="+ext+'&base64='+'aa' ,false);
					blob = file.slice(start,end);//根据长度截取每次需要上传的数据
					fd.append('file_data',blob);//添加数据到fd对象中
					fd.append('filename',filename); //获取文件的名称
					  fd.append("file_size",totalSize);
					xhr.send(fd);//将fd数据上传

					//重新设置开始和结尾
					start = end;
					end = start + LENGTH;
  
				}
				*/

		    	var filename =file.name;
		    	var reader = new FileReader();
		    	//reader.readAsDataURL(file);	//读出 base64
		    	reader.readAsArrayBuffer(file) //:异步按字节读取文件内容，结果用ArrayBuffer对象表示
		    	//reader.readAsBinaryString(file) //:异步按字节读取文件内容，结果用二进制对象表示
		    	reader.onloadend = function (e1) {
		   
	                var binary = this.result;
	                //var base64 = reader.result.split(',')[1]; //base64
	                //console.log(arrayBufferToBase64(binary));
	                //uploadBin(arrayBufferToBase64(binary) , ext ,base64='aa');

				    var xhr = new XMLHttpRequest();
				    xhr.open("POST", "{:url(uploadBin)}?ext="+ext+'&base64='+'aa' );
				    xhr.overrideMimeType("application/octet-stream");
				    //直接发送二进制数据
				    //

				    if(xhr.sendAsBinary){
				        xhr.sendAsBinary(binary);
				    }else{
				        xhr.send(binary);
				    }

					var bin1 = function(datastr) {
					    function byteValue(x) {
					        return x.charCodeAt(0) & 0xff;
					    }
					    var ords = Array.prototype.map.call(datastr, byteValue);
					    var ui8a = new Uint8Array(ords);
					    datastr = (ui8a.buffer);
					};


				    // 监听变化
				    xhr.onreadystatechange = function(e){

				        if(xhr.readyState===4){
				            if(xhr.status===200){
				                // 响应成功       
				            }
				        }
				    };


					//注册相关事件回调处理函数
					xhr.onload = function(e) { 
					  	//console.log(e)
					  	var tmp =this.responseText.split("|||")
					  	if (tmp[0] =='200') {
					  		callback(tmp[1], { title: file });
					  		layer.msg('上传成功');
					  	}else{
					  		layer.msg(tmp[1]);
					  	}
					  	
					  	//alert(this.responseText);
					    if(this.status == 200||this.status == 304){
					        //alert(this.responseText);
					    }
					};
					xhr.ontimeout = function(e) {  };
					xhr.onerror = function(e) { };
					xhr.upload.onprogress = function(e) { 
						console.log(e)
					    if (e.lengthComputable) {
					      var percentComplete = (e.loaded / e.total) * 100;
					      console.log(percentComplete + '% uploaded');
					    }
					};

				    //var id = 'blobid' + (new Date()).getTime();
				    //var blobCache =  tinymce.activeEditor.editorUpload.blobCache;
				    //var base64 = reader.result.split(',')[1];

			    	//var blobInfo = blobCache.create(id, file, base64);
			    	//console.log(reader.result)

		    	};

		    };	  	
		}

	    input.click();
	},

	upload_action: '{:url('upload')}',//required
	upload_file_name: 'file',//required

	images_upload_base_path: '/uploads/attachmenth/',
    imageupload_url: '{:url('upload')}', //图片上传地址
    image_title: false, // 是否开启图片标题设置的选择，这里设置否
    automatic_uploads: true,

 	// 图片异步上传处理函数
    images_upload_handler: (blobInfo, success, failure) => { 
        var xhr, formData;
 
        xhr = new XMLHttpRequest();
        xhr.withCredentials = false;
        xhr.open('POST', '{:url('upload')}');//第一个参数是请求方式，第二个参数是请求地址，我这里配置的是struts的action，如果是其他（PHP等）的可这样配置：xxx.php
 
        xhr.onload = function () {
            var json;
            if (xhr.status !== 200) {
                failure('HTTP Error: ' + xhr.status);
                return;
            }
            json = JSON.parse(xhr.responseText);            
            if (!json || typeof json.location !== 'string') {
            failure('Invalid JSON: ' + xhr.responseText);
                return;
            }
            success(json.location);
        };
 
        formData = new FormData();
        formData.append('file', blobInfo.blob(), blobInfo.filename());
        xhr.send(formData);
    },

    /*
    save_onsavecallback: function(){
          var action = 'savePost';
          var data = tinymce.get('content').getContent();
          $.ajax({
            type: 'POST',
            url: 'PostHandler.php',
            data: {action: action, post_content: data},
            cache: false,
            success: function(response){
              alert(response);
            }
      });
    }
	*/




  });


	//ajax异步上传
	function ajaxUploadBase64File(base64Data){
	    var url = "${ctx}/upload/uploadBase64";
	    $.ajax({
	        url:url,
	        type:"post",
	        data:{base64Data:base64Data},
	        success:function(data){
	            if(data == "success"){
	               alert("上传成功");
	            }else{
	                alert("上传失败");
	            }
	        },
	        error:function(){
	            alert("上传失败");
	        }
	    });
	}; 

	//文件上传
	function uploadBin(binary , ext , base64){
		/*
	    var url = "{:url(uploadBin)}?ext="+ext+'&base64='+base64+'&binary='+binary;
	    $.ajax({
	        url:url,
	        type:"post",
	        //data:{base64Data:base64Data},
	        success:function(data){
	            if(data.code == "0"){
	               alert("上传成功");
	            }else{
	                alert("上传失败");
	            }
	        },
	        error:function(){
	            alert("上传失败");
	        }
	    });

		*/
	    var xhr = new XMLHttpRequest();
	    xhr.open("POST", "{:url(uploadBin)}?ext="+ext+'&base64='+base64);
	    xhr.overrideMimeType("application/octet-stream");
	    //直接发送二进制数据
	    /*
	    if(xhr.sendAsBinary){
	    	
	        xhr.sendAsBinary(binary);
	    }else{
	        xhr.send(binary);
	    }
		*/


		/*二进制发送前进行转换，不然报错无法上传 1.2.2*/
		if (!XMLHttpRequest.prototype.sendAsBinary) {
			XMLHttpRequest.prototype.sendAsBinary = function(datastr) {
			    function byteValue(x) {
			        return x.charCodeAt(0) & 0xff;
			    }
			    var ords = Array.prototype.map.call(datastr, byteValue);
			    var ui8a = new Uint8Array(ords);
			    this.send(ui8a.buffer);
			}
		}



	    console.log(binary)
	    // 监听变化
	    xhr.onreadystatechange = function(e){
	        if(xhr.readyState===4){
	            if(xhr.status===200){
	                // 响应成功       
	            }
	        }
	    }

	}

    //是否支持canvas
    function isCanvasSupported(){
        var elem = document.createElement('canvas');
        return !!(elem.getContext && elem.getContext('2d'));
    };

    /**
     * Base64字符串转成ArrayBuffer数组
     * @param {String} base64
     */
    function base64ToArrayBuffer(base64) {
        var binary_string =  window.atob(base64);
        var len = binary_string.length;
        var bytes = new Uint8Array(len);
        for (var i = 0; i < len; i++){
            bytes[i] = binary_string.charCodeAt(i);
        }
        return bytes.buffer;
    }
 
    /**
     * ArrayBuffer数组转成Base64字符串
     * @param {ArrayBuffer} buffer
     */
    function arrayBufferToBase64(buffer){
        var binary = '';
        var bytes = new Uint8Array(buffer);
        var len = bytes.byteLength;
        for (var i = 0; i < len; i++){
            binary += String.fromCharCode(bytes[i]);
        }
        return window.btoa( binary );
    }

  </script>



<script>

    //window.form.render();
	function hsitoryBack(){
		$.msg.confirm('确定要关闭吗？', function (index) {
			history.back(), $.msg.close(index);
		});
	};
    //require(['angular','plugs/select/xm-Select'], function () {
    //require(['ckeditor', 'plugs/select2/dist/js/select2.min' , 'angular','plugs/select/xm-Select'], function () {
    //window.createEditor('[name="content"]', {height: 250});
		
		
	//var app = angular.module("Newform", []).run(callback);
		

		/**
		 * ajax获取select2下拉框数据（带鼠标滚动分页）
		 * @param selectId 下拉框id
		 * @param options 选项，包含如下字段：
		 * url 数据接口url
		 * pageSize 每次加载的数据条数
		 * name 下拉框显示字段名称
		 * value 下拉框value字段名称
		 * placeholder 默认显示的文字
		 * selected 默认选中项，格式：[{id:1,text:"选项1"},{id:2,text:"选项2"}]
		 * formatResult 返回结果回调函数，可以在该回调中，自定义下拉框数据的显示样式，比如：加入图片等
		 * templateSelection 选中项回调，该参数必须与formatResult参数搭配使用
		 * 注意点1 : 后端接口需返回 data（具体数据）和 total（总页数）两个字段
		 * 注意点2 : 两个自定义的回调函数中，必须要把处理结果return回来，如果没有传入formatResult参数，则采用默认的显示样式
		 */
		function ajaxSelect2 (selectId,options,formatResult,formatSelected) {
			var value = options["value"];
			var name = options["name"];
			var flag = (typeof formatResult === "function") ? true : false;
			var select2Option = {
			
				multiple:"multiple",
				closeOnSelect: true,
				maximumSelectionLength: 10,
				tags: true,
				width: '99%',
				
				language: "zh-CN",
				allowClear: true,
				placeholder: options["placeholder"] || "请选择",
				ajax:{
					url: options["url"],
					type: "get",
					dataType: "json",
					delay: 250,
					data: function(params){
						// 传递到后端的参数
						return {
							// 搜索框内输入的内容
							selectInput: params.term,
							// 当前页
							curPage: params.page || 1,
							// 每页显示多少条记录，默认10条
							pageSize: options["pageSize"] || 10
						};
					},
					cache:true,
					
					processResults: function (res, params) {
						//console.log(res.length)
						params.page = params.page || 1;
						var cbData = [];
						if (flag) {
							cbData = res.data;
						} else {
							var data = res.data;
							var len = res.length;
							for(var i= 0; i<len; i++){
								var option = {"id": res[i][value], "text": res[i][name]};
								cbData.push(option);
							}
						}
						return {
							results: cbData,
							pagination: {
								//more: params.page < len
								more: (params.page * 10) < len
							}
						};
					}
					/*
					processResults: function (data) {
						//console.log(data)
						var arr=[];
						for(var i=0;i<data.length;i++){
							//console.log(data[i].id);
							arr.push({"id":data[i].nickname,"text":data[i].nickname})
						}
						// 后端返回值改成 select2插件想要的格式
						return {
							results: arr
						};
					}*/,				
					
				},
				escapeMarkup: function (markup) {
					// 字符转义处理
					return markup;
				},
				

				templateResult: function (repo) {
					//console.log(repo)
					if (repo.loading) {
						return repo.text;
					} else {
						return repo.text;      //选中 显示的名称
					}
			 
				},
				templateSelection: function (data) {
					console.log(data.id)
					return data.text||data.text;
				},
				// 最少输入N个字符才开始检索，如果想在点击下拉框时加载数据，请设置为 0
				minimumInputLength: 0
			};

			if (flag) {
				select2Option.templateResult = formatResult;
				select2Option.templateSelection = formatSelected;
			}
			var $select =  $("#"+selectId);
			$select.select2(select2Option);
			if (!flag) {
				// 默认选中项设置
				var html = '';
				var values = [];
				var selected = options['selected'];
				if (selected) {
					$.each(selected,function (index,item) {
						values.push(item.id);
						html += '<option value="'+item.id+'">'+item.text+'</option>';
					});
					$select.append(html);
					$select.val(values).trigger('change');
				}
			}		
			
		}


		/*
		var options = {
			url: "{:url('getUserList')}",      // 数据接口url
			pageSize: 10, // 每次加载的数据条数
			value: "id",  // 下拉框value字段名称
			name: "nickname", // 下拉框显示字段名称
			selected: [{id:"丁岳炼",text:"丁岳炼"},{id:"李鑫",text:"李鑫"}]  // 默认选中项，格式：[{id:1,text:"选项1"},{id:2,text:"选项2"}]
		};
		ajaxSelect2("circleId",options);



		var sdata = [
			{id: 1, text:'OPS-COFFEE-1'},
			{id: 2, text:'OPS-COFFEE-2'},
			{id: 3, text:'OPS-COFFEE-3'},
			{id: 4, text:'OPS-COFFEE-4'},
			{id: 5, text:'OPS-COFFEE-5'},
			{id: 6, text:'OPS-COFFEE-6'},
			{id: 7, text:'OPS-COFFEE-7'},
			{id: 8, text:'OPS-COFFEE-8'},
			{id: 9, text:'OPS-COFFEE-9'},
		];

		var sdata = [{$sel2}];
		*/


		//$('.js-example-disabled-resultss').select2({
			
			/*
			ajax: {
				url: "{:url('getUserList')}",
				dataType: 'json',
				type:'GET',
				delay: 250,
				data: function (params) {
					return {
						q: params.term,
					};
				},
				processResults: function (data) {
					//console.log(data)
					var arr=[];
					for(var i=0;i<data.length;i++){
						//console.log(data[i].id);
						arr.push({"id":data[i].nickname,"text":data[i].nickname})
					}
					// 后端返回值改成 select2插件想要的格式
					return {
						results: arr
					};
				},
				cache: false
			},

			*/
			/*
			data: sdata,
			multiple:"multiple",
			closeOnSelect: false,
			maximumSelectionLength: 4,
			allowClear: true,
			tags: true,
			width: '99%',
			//formatNoMatches: '没有符合条件的信息！',//当搜索不到的时候的提示语
			
			
		    placeholder: {
				id: '-1', // the value of the option
				text: '--请选择--'
		    },
		

			language: "zh-CN"
			*/
		//});

		/*
		function callback($rootScope) {
            // 返回列表
            $rootScope.hsitoryBack = function () {
                $.msg.confirm('确定要取消编辑吗？', function (index) {
                    history.back(), $.msg.close(index);
                });
            };
		}*/
		
		var keshifuzeren = xmSelect.render({
			el: '#keshifuzeren', 
			name: 'keshifuzeren',
			toolbar: {
				show: true,
				list: [ 'ALL', 'CLEAR', 'REVERSE' ]
			},

			theme: {
				color: '#0081ff',
			},			
			paging: true,
			pageSize: 10,
			max:2,
			filterable: true,
			data: [
				{$str}
			]
		})		
		
		var shouwenwenyuan = xmSelect.render({
			el: '#shouwenwenyuan', 
			name: 'shouwenwenyuan',
			toolbar: {
				//show: true,
				//list: [ 'ALL', 'CLEAR', 'REVERSE' ]
			},
			paging: true,
			pageSize: 10,
			filterable: true,
			theme: {
				color: '#e54d42',
			},
			model: {
				label: {
					type: 'block',
					block: {
						//最大显示数量, 0:不限制
						showCount: 3,
						//是否显示删除图标
						showIcon: true,
					}
				}
			},
			radio: true,
			data: [
				{$str}
			]
		})	
		
		var bangongshizhuren = xmSelect.render({
			el: '#bangongshizhuren', 
			filterable: true,
			name: 'bangongshizhuren',
			paging: true,
			pageSize: 10,
			toolbar: {
				//show: true,
				//list: [ 'ALL', 'CLEAR', 'REVERSE' ]
			},
			theme: {
				color: '#f37b1d',
			},

			radio: true,
			data: [
				{$str}
			]
		})
		
		var fenguanlingdao = xmSelect.render({
			el: '#fenguanlingdao', 
			filterable: true,
			name: 'fenguanlingdao',
			paging: true,
			pageSize: 10,
			toolbar: {
				show: true,
				list: [ 'ALL', 'CLEAR', 'REVERSE' ]
			},
			theme: {
				color: '#8dc63f',
			},
			model: {
				label: {
					type: 'block',
					block: {
						//最大显示数量, 0:不限制
						showCount: 3,
						//是否显示删除图标
						showIcon: true,
					}
				}
			},
			data: [
				{$str}
			]
		})
		

		
		{if isset($vo) }
		keshifuzeren.setValue([ {$keshifuzeren} ])
		
		bangongshizhuren.setValue([ {$bangongshizhuren} ])
		
		fenguanlingdao.setValue([ {$fenguanlingdao} ])
		
		shouwenwenyuan.setValue([ {$shouwenwenyuan} ])
		
		//zhuyaolingdao.setValue([ {$zhuyaolingdao} ])
		{/if}
		
		
		
    //})
</script>

<script>
    layui.use(['layer','form' ,'jquery','layedit'], function() {
        var layer = layui.layer, $ = layui.jquery ,form = layui.form;
		var layedit = layui.layedit;


	  layedit.set({
		  uploadImage: {
			   url: '{:url('doUploadPic')}' //接口url
			  ,type: 'post' //默认post
		  }
		});
		
		
	  //建立编辑器
	  //layedit.build('content',{
//
		//  height: 300  //设置编辑器高度
	  //}); 
		
        form.render();
    });
	


	$('#saveinfo').click(function(){
		var info = $("#info").val();
		var docid =$("#id").val();
		
		
		var title =$("#title").val();
		var modify =$("#modify").val();
		
		if(info == ''){
			layer.msg('请填写批示意见!',{icon: 5});//失败的表情
			return ;		
		}
		
		if(modify == ''){
			layer.msg('请选择原文有无修改!',{icon: 5});
			return ;		
		}
		
		
		var contents = tinyMCE.activeEditor.getContent();
		//var contents = tinyMCE.editors[0].getContent() ;
		//var contents = tinymce.get('content').getContent()  ;
		
		//encodeURIComponent
		contents = base64.encode(contents); 
		//console.log(contents);
		//return false;
		//alert(info);
		
		var url = "/document/news/saveinfo.html";
		$.ajax({
			url:url,
			type:'post',
			data:'info='+info+'&docid='+docid+'&contents='+contents+'&title='+title+'&modify='+modify,
			beforeSend:function () {
				
				this.layerIndex = layer.load(0, { shade: [0.5, '#393D49'] });
			},
			success:function(data){
				if(data.status == 'error'){
					layer.msg(data.msg,{icon: 5});//失败的表情
					return;
				}else if(data.status == 'success'){
					//layer.msg(data.msg,{icon: 6});
					layer.msg(data.msg, {
						icon: 6,//成功的表情
						time: 2000 //1秒关闭（如果不配置，默认是3秒）
					}, function(){
						//location.reload();
						window.location.href="/admin.html#/document/news/index.html?spm=m-73-74-75";
					});
				}
			},
			complete: function () {
				layer.close(this.layerIndex);
			},
		});
		return false;//阻止表单跳转
	});


	function quote(file){
	
		var url = "/document/news/quote.html";
		$.ajax({
			url:url,
			type:'post',
			data:'file='+file,
			beforeSend:function () {
				
				this.layerIndex = layer.load(0, { shade: [0.5, '#393D49'] });
			},
			success:function(data){
				if(data.status == 'error'){
					layer.msg(data.msg,{icon: 5});//失败的表情
					return;
				}else if(data.status == 'success'){
					//layer.msg(data.msg,{icon: 6});
					layer.msg(data.msg, {
						icon: 6,//成功的表情
						time: 2000 //1秒关闭（如果不配置，默认是3秒）
					}, function(){
						tinymce.activeEditor.setContent(data.data)
						//location.reload();
						//window.location.href="/admin.html#/document/news/index.html?spm=m-73-74-75";
					});
				}
			},
			complete: function () {
				layer.close(this.layerIndex);
			},
		});
	
	}





</script>


{/block}